
// pages/life/add/add.js
const app = getApp()
import Notify from '@vant/weapp/notify/notify';
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		radio:'0',
		name:'',
		place:'',
		fileList: [],
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},
	onChange(event){
		this.setData({
      radio: event.detail,
    });
	},
	submit() {
		var user=wx.getStorageSync('user')
		var question = JSON.stringify({
			thing:this.data.name,
			place:this.data.place,
			uid:user.id,
			type:this.data.radio,
			pic:this.data.fileList[0]!=null?this.data.fileList[0].url:'',
			done:0
		})
		app.request({
			url: app.globalData.apiUrl + '/found/'+question,
			method: 'POST',
		}).then(res => {
			if (res.statusCode == 200) {
				Notify({
          type: 'primary',
          message: '发布成功'
        })
				setTimeout(() => {
					// wx.navigateBack({
					// 	delta: 1,
					// 	success: function (e) {
					// 		var page = getCurrentPages().pop();
					// 		if (page == undefined || page == null) return;
					// 		page.onLoad();
					// 	}
					// })
					wx.navigateBack({
						delta: 1,
					}) //返回上一个页面更新数据
				}, 1000);
			} else {
				Notify('服务错误，稍后重试');
			}
		})
	},
	  //上传图片之前
		beforeRead(event) {
			const { file, callback } = event.detail;
			console.log(file)
			if (file.size > 10 * 1024 * 1024) {
				wx.showToast({
					title: '文件大小不能超过 10M!',
					icon: 'none'
				})
				callback(false);
			}
			let name = file.url.substring(file.url.lastIndexOf("."));
			if (name != '.png' && name != '.jpg') {
				wx.showToast({
					title: '图片必须是 .png 或 .jpg!',
					icon: 'none'
				})
				callback(false);
			}
			callback(true)
		},
		//上传图片
		afterRead(event) {
			console.log('上传图片')
			const {
				file
			} = event.detail;
			let that = this
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			wx.uploadFile({
				url: app.globalData.fileApi+'/pic',
				method: 'POST',
				filePath: file.url,
				name: 'file',
				formData: {
					user: 'test'
				},
				header: {
					token: wx.getStorageSync('token')
				},
				success(res) {
					var data = JSON.parse(res.data)
					const {
						fileList = []
					} = that.data.fileList;
					fileList.push({
						...file,
						url: data.data
					});
					that.setData({
						fileList
					});
				},
			});
		},
		// 点击删除图片
		deleteImg() {
			app.request({
				url: app.globalData.fileApi + '/pic',
				method: 'DELETE',
				data: {
					fileName: this.data.fileList[0].url,
				}
			}).then(res => {
				if (res.statusCode == 200) {
					this.setData({
						fileList: [],
					})
					this.data.user.icon=null;
					wx.setStorageSync('user', this.data.user)
				} else {
					Notify('服务错误，稍后重试');
				}
			})
		},
})